# users/serializers.py

from rest_framework import serializers
from django.contrib.auth import authenticate
from .models import User, UserProfile, DailyActivity, EmailVerification, Avatar
from django.utils import timezone
from django.contrib.auth.password_validation import validate_password
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError

class RegisterSerializer(serializers.ModelSerializer):
    username = serializers.CharField(
        required=True,
        max_length=16,
        validators=[
            RegexValidator(
                regex='^[A-Za-z0-9]+$',
                message='用户名只能包含字母和数字。',
                code='invalid_username'
            )
        ]
    )
    email = serializers.EmailField(required=True)
    password = serializers.CharField(write_only=True, required=True, validators=[validate_password])
    confirm_password = serializers.CharField(write_only=True, required=True)
    verification_code = serializers.CharField(write_only=True, required=True, max_length=6)
    avatar = serializers.ImageField(required=False, allow_null=True)

    class Meta:
        model = User
        fields = ('username', 'email', 'password', 'confirm_password', 'verification_code', 'avatar')

    def validate_username(self, value):
        # 检查用户名是否在禁用列表中
        if value.lower() in User.DISALLOWED_USERNAMES:
            raise serializers.ValidationError("该用户名不允许使用。")
        return value

    def validate(self, attrs):
        if attrs['password'] != attrs['confirm_password']:
            raise serializers.ValidationError({"password": "密码和确认密码不匹配。"})

        # 验证验证码
        try:
            verification = EmailVerification.objects.get(email=attrs['email'], code=attrs['verification_code'])
        except EmailVerification.DoesNotExist:
            raise serializers.ValidationError({"verification_code": "验证码无效或已过期。"})

        if verification.is_expired():
            raise serializers.ValidationError({"verification_code": "验证码已过期。"})

        return attrs

    def create(self, validated_data):
        verification = EmailVerification.objects.get(email=validated_data['email'], code=validated_data['verification_code'])
        user = User.objects.create(
            username=validated_data['username'],
            email=validated_data['email'],
        )
        user.set_password(validated_data['password'])
        user.is_verified = True
        user.save()

        # 创建用户个人资料
        UserProfile.objects.create(user=user)

        # 处理头像（如果提供）
        avatar = validated_data.get('avatar', None)
        if avatar:
            user.profile.avatar = avatar
            user.profile.is_avatar_approved = False  # 默认未审核
            user.profile.save()

        # 删除已使用的验证码
        verification.delete()

        return user

class LoginSerializer(serializers.Serializer):
    email = serializers.EmailField(required=True)
    password = serializers.CharField(write_only=True, required=True)

    def validate(self, attrs):
        user = authenticate(email=attrs['email'], password=attrs['password'])
        if not user:
            raise serializers.ValidationError({"detail": "无法登录。请检查邮箱和密码。"})
        if not user.is_verified:
            raise serializers.ValidationError({"detail": "邮箱未验证。"})
        attrs['user'] = user
        return attrs

class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = '__all__'

class DailyActivitySerializer(serializers.ModelSerializer):
    class Meta:
        model = DailyActivity
        fields = '__all__'

class EmailVerificationSerializer(serializers.Serializer):
    email = serializers.EmailField()

    def validate_email(self, value):
        if User.objects.filter(email=value).exists() and User.objects.get(email=value).is_verified:
            raise serializers.ValidationError("该邮箱已被注册并验证。")
        return value

class AvatarSerializer(serializers.ModelSerializer):
    class Meta:
        model = Avatar
        fields = ('id', 'name', 'image')
